import { guid } from './guid';
export class QueueManager {
    static Current: QueueManager = new QueueManager();

    private timer;
    private timerOn: boolean;
    private list: QueueItem[] = [];

    Add(action) {
        let queueItem: QueueItem = {
            key: guid(),
            doing: false,
            action: action
        };

        this.list.push(queueItem);
        this.StartTimer(100);
    }
    
    /**
     * 中断循环队列，清空请求列表
     */
    BreakOff() {
        this.list = [];
    }

    private SetTimer(interval: number) {
        this.timer = setInterval(this.timerAction.bind(this), interval);
    }
    private ClearTimer() {
        clearInterval(this.timer);
    }

    private StartTimer(interval: number) {
        if (!this.timerOn) {
            this.timerOn = true;
            this.SetTimer(interval);
        }
    }
    private StopTimer() {
        this.timerOn = false;
        this.ClearTimer();
    }
    private timerAction() {
        this.ClearTimer();
        let l = this.list.filter(x => x.doing == false || x.doing == undefined && (x.error == undefined));
        let count = l.length > 10 ? 10 : l.length;
        if (count > 0) {
            for (let i = 0; i < count; i++) {
                let queueItem = l[i];
                queueItem.doing = true;
                queueItem.action()
                    .then(() => {
                        queueItem.doing = false;
                        let index = this.list.findIndex(x => x.key == queueItem.key);
                        this.list.splice(index, 1);
                    })
                    .catch((err) => {
                        queueItem.doing = false;
                        queueItem.error = err;
                    });
            }
            this.SetTimer(100);
        }
        else {
            this.StopTimer();
        }
    }
}

export interface QueueItem {
    key;
    value?;
    action: () => Promise<any>;
    doing: boolean;
    error?: string;
}